package com.gadarts.parashoot.player;


import com.gadarts.parashoot.GameModel;
import com.gadarts.parashoot.GameObject;
import com.gadarts.parashoot.GameView;
import com.gadarts.parashoot.Sprite;
import com.gadarts.parashoot.utils.C;
import com.gadarts.parashoot.utils.Utils;
import com.gadarts.parashoot.utils.ViewUtils;

public class Turret extends GameObject {

	private boolean shoot = false, readyToShoot = true;
	private String animationTimer, reloadTimer;

	public Turret(GameModel model, GameView view, Sprite sprite, int x,
			int y, int direction, int depth) {
		super(model, view, sprite, x, y, 0, direction, depth, true);
		super.child = this;
		setDirection(direction);
		String timerName = C.Weapons.TimersNames.TURRET_SHOOTING_ANIMATION;
		animationTimer = Utils.setTimer(model, timerName);
		reloadTimer = Utils.setTimer(model,
				C.Weapons.TimersNames.TURRET_RELOAD_TIME);
	}

	@Override
	public void update() {
		super.update();
		shoot();// Changes image to shooting and creates a bullet.
	}

	private void shoot() {// Changes image to shooting and creates a bullet.
		if (readyToShoot) {// Shoot only if it's ready.
			if (shoot) {// Only if the player presses the button.
				int cosPos = ((int) (Math.cos(Math.toRadians(direction)) * getWidth()));
				int sinPos = ((int) (Math.sin(Math.toRadians(direction)) * getWidth()));
				Sprite bulletImage = view
						.getSprite(C.Weapons.Sprites.Names.BULLET_IMAGE);
				model.createBullet(bulletImage, x + cosPos, y + sinPos,
						ViewUtils.calculatePosX(C.Weapons.CannonBall.SPEED,
								view.getWidth()), direction, true, -1);
				currentFrame = C.Weapons.Sprites.FramesIndex.TURRET_SHOOTING;
				Utils.updateTimer(model, animationTimer);
				Utils.updateTimer(model, reloadTimer);
				readyToShoot = false;
			}
		} else {
			int animationTime = C.Weapons.Timers.TURRET_SHOOTING_ANIMATION;
			int reloadTime = C.Weapons.Timers.TURRET_RELOAD_TIME;
			if (Utils.checkTiming(model, animationTimer, animationTime))
				currentFrame = C.Weapons.Sprites.FramesIndex.TURRET_IDLE;
			if (Utils.checkTiming(model, reloadTimer, reloadTime))
				readyToShoot = true;
		}
	}

	@Override
	protected void setDirection(int direction) {
		if (rotateChange < 0) {// Don't go under.
			if (direction <= 180 + rotateChange)
				rotateChange = 0;
		} else if (rotateChange > 0) {
			if (direction >= 360 - rotateChange)
				rotateChange = 0;
		} else
			rotateChange = 0;
		this.direction = direction;
		while (direction >= 360)
			// Direction needs to be in degrees.
			direction -= 360;
		while (direction < 0)
			direction += 360;
		matrix.setRotate(direction, 0, 0);
		matrix.postTranslate(x, y);
	}

	public void setShootingState(boolean state) {
		shoot = state;
	}

}
